import React, { useEffect, useRef, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Form, message, Modal, notification, Space, Table } from 'antd'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import { useFormBase, useFormtaginfo, useFormCalc, useFormFabric, useFormColor, useFormUpload } from './useForm'
import { useForm } from 'antd/es/form/Form'
import {
  editTagPrice,
  getProductColorPageList,
  getProductFabricPageList,
  getProductSpuInfoInfoById,
  getSizeListByClassId,
  spuEditAssociatedFabric,
  spuEditBaseInfo,
  spuEditMeasureInfo,
  spuEditPicture,
  spuEditSkuInfo,
  spuEditTagInfo,
  spuEditUpdateStatus,
} from '@/api/goods'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './detail.less'
import { useAppSelector } from '@/store/hooks'
import dayjs from 'dayjs'
import { ITableDataColor, ITableDataFabric } from '../Style/types'
import { useFabricDel, useColorDel } from './columns'
import { ISkuType } from './types'
import { onValuesChange } from '@/utils/onValuesChange'
import LogsDrawer from '@/components/LogsDrawer'
import useViewLogs from '@/hooks/useViewLogs'
import { OperationLogType, STATUSNUM } from '@/constant'
import PermissionButton from '@/components/PermissionButton'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import { PlusOutlined } from '@ant-design/icons'
import useSearchFabric from '@/hooks/useSearchFabric'
import useModal from '@/hooks/useModal'
import EditTable from './components/EditTable'
const Index: React.FC = () => {
  let ColorTimeout: ITimeoutType
  const inputRef = useRef<any>(null)
  const [FormStylebaseinfo] = useForm()
  const [FormStyletaginfo] = useForm()
  const [FormStyleFabric] = useForm()
  const [FormStyleColor] = useForm()
  const [FormStyleCalc] = useForm()
  const [FormStyleUpload] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [isLoading, setisLoading] = useState<boolean>(false)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [productTemplateVO, setproductTemplateVO] = useState<IGoodsTemplateType>(null)
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    { label: '款式编码', key: 'spuCode', content: '-' },
    { label: '助记码', key: 'designCode', content: '-' },
    { label: '款式分类', key: 'className', content: '-' },
    { label: '年份', key: 'year', content: '-' },
    { label: '适销季节', key: 'seasonName', content: '-' },
    { label: '采购方式', key: 'purchaseTypeName', content: '-' },
    { label: '开发季', key: 'devSeasonName', content: '-' },
    { label: '商品企划编号', key: 'planNo', content: '-' },
    { label: '开发定位', key: 'devLocationName', content: '-' },
    {
      label: '企划毛利率',
      key: 'planRate',
      content: '-',
      format: (info) => (info.planRate ? info.planRate + '%' : '-'),
    },
    {
      label: '毛利率下限',
      key: 'profitRateLowerLimit',
      content: '-',
      format: (info) => (info.profitRateLowerLimit ? info.profitRateLowerLimit + '%' : '-'),
    },
  ])
  const [baseinfoList, setbaseinfoList] = useState<IDesListType>([
    { label: '款式名称', key: 'spuName', content: '-' },
    { label: '主供应商', key: 'mainSupplierName', content: '-' },
    { label: '工厂类型', key: 'factoryTypeCode', content: '-' },
    { label: '其他可生产供应商', key: 'otherSupplierNameList', content: '-' },
    { label: '吊牌价', key: 'originSalePrice', content: '-' },
    { label: '价格属性', key: 'pricePropertyName', content: '-' },
    { label: '定价权限', key: 'priceAuthName', content: '-' },
    { label: '款式成本', key: 'spuCost', content: '-' },
    {
      label: '实际毛利率',
      key: 'realProfitRate',
      content: '-',
      format: (info) => (info.realProfitRate ? info.realProfitRate + '%' : '-'),
    },
    { label: '厂家款号', key: 'factorySpuCode', content: '-' },
    { label: '上市日期', key: 'releaseSeasonDate', content: '-' },
    { label: '过季日期', key: 'overSeasonDate', content: '-' },
    { label: '季节分组', key: 'seasonGroupName', content: '-' },
    { label: '适销年龄段', key: 'suitAgeGroupName', content: '-' },
    { label: '商品等级', key: 'productLevelName', content: '-' },
    { label: '设计师/买手', key: 'designerName', content: '-' },
  ])
  const taginfoListOrigin: IDesListType = [
    { label: '商品系列', key: 'productSeries', content: '-', showKey: 'productSeries' },
    { label: '版型', key: 'patternType', content: '-', showKey: 'patternType' },
    { label: '领型', key: 'collarType', content: '-', showKey: 'collarType' },
    { label: '花型', key: 'flowerType', content: '-', showKey: 'flowerType' },
    { label: '杯型', key: 'moduleType', content: '-', showKey: 'moduleType' },
    { label: '后比', key: 'laterThan', content: '-', showKey: 'laterThan' },
    { label: '模杯材质', key: 'moldCupMaterial', content: '-', showKey: 'moldCupMaterial' },
    { label: '模杯厚度', key: 'moldCupThickness', content: '-', showKey: 'moldCupThickness' },
    { label: '模杯形状', key: 'moldCupShape', content: '-', showKey: 'moldCupShape' },
    { label: '排扣', key: 'breasted', content: '-', showKey: 'breasted' },
    { label: '厚度', key: 'thicknessCode', content: '-', showKey: 'thicknessCode' },
    { label: '功能', key: 'functionType', content: '-', showKey: 'functionType' },
    { label: '风格', key: 'styleName', content: '-', showKey: 'styleCode' },
    { label: '图案布局', key: 'patternLayoutName', content: '-', showKey: 'patternLayoutCode' },
    { label: '元素', key: 'elementName', content: '-', showKey: 'elementCode' },
    { label: '工艺', key: 'technicsName', content: '-', showKey: 'technicsCode' },
    { label: '面料', key: 'fabricType', content: '-', showKey: 'fabricType' },
    { label: '适卖温度', key: 'sellTempCode', content: '-', showKey: 'sellTempCode' },
    { label: '克重', key: 'gramWeight', content: '-', showKey: 'gramWeight' },
    { label: '价格带', key: 'priceTagCode', content: '-', showKey: 'priceTagCode' },
    { label: '年龄段', key: 'ageCode', content: '-', showKey: 'ageCode' },
  ]
  const [taginfoList, settaginfoList] = useState<IDesListType>(taginfoListOrigin)
  const [calcList, setcalcList] = useState<IDesListType>([
    { label: '外包方式', key: 'outPackageTypeName', content: '-' },
    { label: '中包标识', key: 'midPackageTypeName', content: '-' },
    { label: '包装方式', key: 'packageTypeName', content: '-' },
    { label: '计量单位', key: 'weightUnitName', content: '-' },
    { label: '内箱数', key: 'inPackageNum', content: '-' },
    { label: '外箱数', key: 'outPackageNum', content: '-' },
  ])
  const REQUIRED_FIELDS = [
    'intensiveStatus',
    'useSite',
    'fabricName',
    'fabricSupplier',
    'fabricSpec',
    'fabricComposition',
    'fabricBreadth',
    'gramWeight',
  ]
  //基础信息
  const [isbaseinfoEdit, setisbaseinfoEdit] = useState<boolean>(false)
  //标签信息
  const [istaginfoEdit, setistaginfoEdit] = useState<boolean>(false)
  //fabric
  const [isfabricEdit, setisfabricEdit] = useState<boolean>(false)
  //color
  const [iscolorEdit, setiscolorEdit] = useState<boolean>(false)
  //calc
  const [iscalcEdit, setiscalcEdit] = useState<boolean>(false)
  //upload
  const [isuploadEdit, setisuploadEdit] = useState<boolean>(false)
  //面料option
  const { FabricOption, setFabricOption, handleSearchFabric } = useSearchFabric()
  const [FabricList, setFabricList] = useState<any[]>([])
  //颜色option
  const [ColorOptions, setColorOptions] = useState<IOptionItem[]>([])
  const [SizeGroupOptions, setSizeGroupOptions] = useState<IOptionItem[]>([])
  const [sizeRangeInfos, setsizeRangeInfos] = useState<
    {
      enableStatus: number
      label: string
      sizeDetailCode: string
      sizeDetailId: string
      sizeDetailName: string
      sizeGroupId: string
      sizeGroupName: string
      value: string
    }[]
  >([])
  //SKU信息添加
  const [skuInfo, setskuInfo] = useState<ISkuType>({})
  const [skuInfoList, setskuInfoList] = useState<ISkuType[]>([])
  const mainSupplierCode = Form.useWatch('mainSupplierCode', FormStylebaseinfo)
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier()
  const { SupplierOption: SupplierOptionOther, handleSearchSupplier: handleSearchSupplierOther } = useSearchSupplier()
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [query] = useSearchParams()
  const spuId = query.get('spuId')
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'spuCode',
    OperationLogType.PRODUCTSPU,
  )
  const tagPriceModal = useModal({
    onSuccess: () => {
      message.success(
        <span>
          吊牌价修正成功，<span style={{ color: 'red', fontWeight: 500 }}>若商品已下单，请更新订单关联吊牌价</span>
        </span>,
      )
    },
    onReload: () => {
      getDetail()
    },
  })
  useEffect(() => {
    if (spuId) {
      getDetail()
    }
  }, [])

  useEffect(() => {
    if (productTemplateVO && productTemplateVO?.notShow?.length > 0) {
      const filtertaginfoList = taginfoListOrigin.filter((item) => !productTemplateVO?.notShow?.includes(item.showKey!))
      handleDetailFactory(filtertaginfoList, detailInfo, settaginfoList)
    } else {
      handleDetailFactory(taginfoListOrigin, detailInfo, settaginfoList)
    }
  }, [detailInfo, productTemplateVO])

  const getDetail = async () => {
    const res = await getProductSpuInfoInfoById({ spuId })
    if (res.code === 200) {
      const details = res.data
      details?.productTemplateVO && setproductTemplateVO(details.productTemplateVO)
      setDetail(details)
      details?.spuCode && (document.title = details.spuCode)
      details?.mainSupplierName && handleSearchSupplier(details?.mainSupplierName)
      handleDetailFactory(
        details.purchaseType === 1
          ? [
              { label: '款式编码', key: 'spuCode', content: '-' },
              { label: '助记码', key: 'designCode', content: '-' },
              { label: '款式分类', key: 'className', content: '-' },
              { label: '年份', key: 'year', content: '-' },
              { label: '适销季节', key: 'seasonName', content: '-' },
              { label: '采购方式', key: 'purchaseTypeName', content: '-' },
            ]
          : desInfoList,
        details,
        setDesInfoList,
      )
      handleDetailFactory(baseinfoList, details, setbaseinfoList)
      handleDetailFactory(calcList, details, setcalcList)
      // FabricList FabricOption处理
      handleSearchFabric('', details.purchaseType === 1 ? '@' : details?.devSeasonName, details?.bigClassId)
      const fabric_list =
        details?.fabricConfigVOS?.map((item: any, index: number) => {
          return {
            ...item,
            tempId: index + new Date().getTime(),
          }
        }) || []
      setFabricList([...fabric_list])
      // ColorList ColorOption处理
      if (details.skuInfoVOS && details.skuInfoVOS.length > 0) {
        setskuInfoList(details.skuInfoVOS || [])
      }
      FormStyleUpload.setFieldValue('mainPicFileId', details?.mainPicFileId || null)
      FormStyleUpload.setFieldValue('otherPicFileIdList', details?.otherPicFileIdList || null)
    }
  }
  const startEdit = async (
    setisEdit: React.Dispatch<React.SetStateAction<boolean>>,
    callback: (data?: any) => Promise<any>,
  ) => {
    setispedding(true)
    const res = await callback().finally(() => setispedding(false))
    console.log(res, 'res')
    if (res.code === 200) {
      setisEdit(false)
      message.open({
        type: 'success',
        content: '操作成功',
        duration: 5,
      })
      getDetail()
    }
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }
  const handleSearchColor = (newValue = '') => {
    if (ColorTimeout) {
      clearTimeout(ColorTimeout)
      ColorTimeout = null
    }
    const getOptions = async () => {
      const res = await getProductColorPageList<ITableDataColor>({ colorGroupSearchName: newValue, enableStatus: 1 })
      if (res.code === 200) {
        const data =
          res?.data?.list?.map((item) => {
            return {
              label: item.colorDetailName,
              code: item.colorCode,
              value: item.colorDetailId + '',
              rgbValue: item.rgbValue,
              picUrl: item?.picUrl,
            }
          }) || []
        setColorOptions(data)
      }
    }
    ColorTimeout = setTimeout(getOptions, 500)
  }
  const getProductPresetConfigInfos = async (tinyClassId: number | string) => {
    const res = await getSizeListByClassId<{ sizeDetailId: number; sizeDetailName: string }>({ tinyClassId })
    if (res.code === 200) {
      const data =
        res?.data?.map((item) => {
          return {
            ...item,
            label: item.sizeDetailName,
            value: item.sizeDetailId,
          }
        }) || []
      setSizeGroupOptions(data)
    }
  }
  const onStatus = async (info: ISkuType, index: number) => {
    setisLoading(true)
    const res = await spuEditUpdateStatus({
      enableStatus: info.enableStatus == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE,
      skuId: info?.skuId,
      spuCode: detailInfo.spuCode,
    }).finally(() => setisLoading(false))
    if (res.code === 200) {
      message.success('操作成功')
      skuInfoList[index].enableStatus =
        skuInfoList[index].enableStatus == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE
      setskuInfoList([...skuInfoList])
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: { bizCode: string; errorMsg: string }) => {
        return (
          <div key={item.bizCode}>
            bizCode：{item.bizCode}，errorMsg：{item.errorMsg}
          </div>
        )
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleClickAdd = async () => {
    if (skuInfo.colorCode && skuInfo.sizeCode) {
      const hasCommon = skuInfoList?.filter(
        (item) => item.colorCode == skuInfo.colorCode && item.sizeCode == skuInfo.sizeCode,
      )
      if (hasCommon.length > 0) {
        message.warning('款式色、尺码重复')
        return
      }
      if (skuInfo.netWeight && skuInfo.grossWeight && skuInfo.netWeight > skuInfo.grossWeight) {
        message.warning('净重不能大于毛重！')
        return
      }
      setskuInfoList([...skuInfoList, skuInfo])
      setskuInfo({})
      FormStyleColor.resetFields()
    } else {
      message.warning('请添加款式色、尺码范围后再进行添加！')
    }
  }

  const editTagPriceReq = (vals: any) => {
    // 数据处理
    return editTagPrice({ ...vals, spuCode: detailInfo.spuCode })
  }
  return (
    <DetailContainer
      className="goods_manage_add_page"
      footer={
        <Space>
          {spuId && Object.keys(detailInfo).length > 0 && (
            <Button type="primary" ghost onClick={() => viewLogs(detailInfo)}>
              查看日志
            </Button>
          )}
        </Space>
      }
    >
      <Descriptions title="" list={desInfoList}></Descriptions>
      <Descriptions
        title="基础信息"
        list={isbaseinfoEdit ? [] : baseinfoList}
        extra={
          <Space>
            <PermissionButton type="primary" permission="fixTagPrice" onClick={() => tagPriceModal.openModal()}>
              修正吊牌价
            </PermissionButton>
            <PermissionButton
              permission="editSpuBase"
              loading={ispedding}
              type="primary"
              onClick={async () => {
                if (isbaseinfoEdit) {
                  const data = await FormStylebaseinfo.validateFields()
                  const entries = Object.entries(data).map(([key, value]) => {
                    return [key, value === undefined || value === null ? '' : value]
                  })
                  const filterData = Object.fromEntries(entries) as Record<string, any>
                  const params = {
                    ...filterData,
                    spuId,
                    spuCode: detailInfo.spuCode,
                    overSeasonDate: data.overSeasonDate && dayjs(data.overSeasonDate).format('YYYY-MM-DD HH:mm:ss'),
                    releaseSeasonDate:
                      data.releaseSeasonDate && dayjs(data.releaseSeasonDate).format('YYYY-MM-DD HH:mm:ss'),
                    otherSupplierCodeList:
                      filterData?.otherSupplierCodeList && filterData?.otherSupplierCodeList.length > 0
                        ? filterData?.otherSupplierCodeList.join(',')
                        : '',
                  }
                  startEdit(setisbaseinfoEdit, () => spuEditBaseInfo(params))
                } else {
                  setisbaseinfoEdit(true)
                  FormStylebaseinfo.setFieldsValue({
                    ...detailInfo,
                    releaseSeasonDate: detailInfo.releaseSeasonDate && dayjs(detailInfo.releaseSeasonDate),
                    overSeasonDate: detailInfo.overSeasonDate && dayjs(detailInfo.overSeasonDate),
                    otherSupplierCodeList: detailInfo?.otherSupplierCodeList
                      ? detailInfo?.otherSupplierCodeList?.split(',')
                      : null,
                    realProfitRate:
                      detailInfo?.originSalePrice > 0 &&
                      (
                        ((detailInfo?.originSalePrice - detailInfo.spuCost) / detailInfo?.originSalePrice) *
                        100
                      ).toFixed(2),
                  })
                }
              }}
            >
              {isbaseinfoEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isbaseinfoEdit ? (
              <Button
                onClick={() => {
                  setisbaseinfoEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline
          className="sep_forminline_style"
          editConfig={useFormBase({
            DICTDATA,
            SupplierOption,
            handleSearchSupplier,
            SupplierOptionOther,
            handleSearchSupplierOther,
            mainSupplierCode,
            detailInfo,
            FormStylebaseinfo,
          })}
          form={FormStylebaseinfo}
          onValuesChange={(changedValues) =>
            onValuesChange(changedValues, ['spuName', 'factorySpuCode', 'designerName'], FormStylebaseinfo)
          }
        />
      </Descriptions>
      <Descriptions
        title="标签信息"
        list={istaginfoEdit ? [] : taginfoList}
        extra={
          <Space>
            <PermissionButton
              permission="editSpuLable"
              loading={ispedding}
              type="primary"
              onClick={async () => {
                if (istaginfoEdit) {
                  const data = await FormStyletaginfo.validateFields()
                  const entries = Object.entries(data).map(([key, value]) => {
                    return [key, value === undefined || value === null ? '' : value]
                  })
                  const filterData = Object.fromEntries(entries) as Record<string, any>
                  const params = {
                    ...filterData,
                    spuId,
                    spuCode: detailInfo.spuCode,
                    functionType: data.functionType ? data?.functionType?.join(',') : '',
                  }
                  console.log(params, 'params')
                  startEdit(setistaginfoEdit, () => spuEditTagInfo(params))
                } else {
                  setistaginfoEdit(true)
                  FormStyletaginfo.setFieldsValue({
                    ...detailInfo,
                    ageCode: detailInfo.ageCode,
                    functionType: detailInfo?.functionType ? detailInfo.functionType.split(',') : null,
                  })
                }
              }}
            >
              {istaginfoEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {istaginfoEdit ? (
              <Button
                onClick={() => {
                  setistaginfoEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline
          editConfig={useFormtaginfo({ DICTDATA, productTemplateVO })}
          form={FormStyletaginfo}
          onValuesChange={(changedValues) =>
            onValuesChange(
              changedValues,
              ['productSeries', 'patternType', 'collarType', 'flowerType', 'moduleType', 'fabricType'],
              FormStyletaginfo,
            )
          }
        />
      </Descriptions>
      <Descriptions
        title="面料"
        extra={
          <Space>
            <PermissionButton
              permission="editSpuFabric"
              type="primary"
              loading={ispedding}
              onClick={async () => {
                if (isfabricEdit) {
                  if (
                    FabricList.some(
                      (item) =>
                        item?.intensiveStatus == 1 &&
                        REQUIRED_FIELDS.some((field) => item?.[field] == undefined || item?.[field] === ''),
                    )
                  ) {
                    message.warning('集约面料请填写完整面料信息！')
                    return
                  }
                  if (FabricList.some((item) => item?.intensiveStatus == 0 && (!item?.useSite || !item?.fabricName))) {
                    message.warning('非集约面料请填写使用部位和面料名称！')
                    return
                  }
                  const newFabricList = FabricList?.map((item, index) => {
                    const { tempId, isEdit, ...reset } = item
                    return {
                      ...reset,
                      mainFabric: index === 0 ? 1 : 0,
                    }
                  })
                  const params = {
                    spuId,
                    spuCode: detailInfo.spuCode,
                    productSpuFabricDTOS: newFabricList,
                  }
                  startEdit(setisfabricEdit, () => spuEditAssociatedFabric(params))
                } else {
                  setisfabricEdit(true)
                }
              }}
            >
              {isfabricEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isfabricEdit ? (
              <Button
                onClick={() => {
                  setisfabricEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="flex_column">
          <div className="custom_table_style manage_fabricedit_wrap" style={{ width: 1200 }}>
            <EditTable
              showAddBtn={isfabricEdit}
              columns={useFabricDel({
                isEdit: isfabricEdit,
                FabricList,
                setFabricList,
                FabricOption,
                handleSearchFabric,
                SupplierOption,
                handleSearchSupplier,
                detailInfo,
                inputRef,
              })}
              tableData={FabricList}
              settableData={setFabricList}
            />
          </div>
        </div>
      </Descriptions>
      <Descriptions
        title="SKU信息"
        extra={
          <Space>
            <PermissionButton
              permission="editSpuSku"
              loading={ispedding}
              type="primary"
              onClick={async () => {
                if (iscolorEdit) {
                  const params = {
                    spuId,
                    spuCode: detailInfo.spuCode,
                    skuInfoEditDTOS: skuInfoList,
                  }
                  const errorList = skuInfoList.filter(
                    (item) => item.netWeight && item.grossWeight && item.netWeight > item.grossWeight,
                  )
                  if (errorList.length > 0) {
                    notification.open({
                      type: 'warning',
                      message: '净重不能大于毛重',
                      description: (
                        <div>
                          {errorList.map((item: any) => {
                            return <div key={item.skuCode}>skuCode：{item.skuCode}</div>
                          })}
                        </div>
                      ),
                    })
                    return
                  }
                  startEdit(setiscolorEdit, () => spuEditSkuInfo(params))
                } else {
                  getProductPresetConfigInfos(detailInfo.classId)
                  setiscolorEdit(true)
                }
              }}
            >
              {iscolorEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {iscolorEdit ? (
              <Button
                onClick={() => {
                  setiscolorEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="flex_row">
          <div className="sep_formiline_style" style={{ display: !iscolorEdit ? 'none' : 'block' }}>
            <EditFormInline
              editConfig={useFormColor({
                isEdit: iscolorEdit,
                ColorOptions,
                handleSearchColor,
                SizeGroupOptions,
                setsizeRangeInfos,
                skuInfo,
                setskuInfo,
                iscolorEdit,
                handleClickAdd,
              })}
              form={FormStyleColor}
              initialValues={{ colorDetailIds: [] }}
              onValuesChange={(changedValues) => onValuesChange(changedValues, ['carryOverCode'], FormStyleColor)}
            />
          </div>
          <div className="custom_table_style">
            <Table
              bordered
              columns={useColorDel({
                isEdit: iscolorEdit,
                skuInfoList,
                setskuInfoList,
                onStatus,
                isStatusBtnCode: buttonCodeList?.includes('skuDetailStatus'),
                isLoading,
              })}
              dataSource={skuInfoList}
              rowKey={(rows) => rows.colorCode! + rows.sizeCode!}
              scroll={{ y: 400 }}
              pagination={false}
              rowClassName={(_, index) => {
                return index % 2 === 0 ? '' : 'zebra-row-odd'
              }}
            />
          </div>
        </div>
      </Descriptions>
      <Descriptions
        title="计量信息"
        list={iscalcEdit ? [] : calcList}
        extra={
          <Space>
            <PermissionButton
              permission="editSpuMeasure"
              loading={ispedding}
              type="primary"
              onClick={async () => {
                if (iscalcEdit) {
                  const data = await FormStyleCalc.validateFields()
                  const entries = Object.entries(data).map(([key, value]) => {
                    return [key, value === undefined || value === null ? '' : value]
                  })
                  const filterData = Object.fromEntries(entries) as Record<string, any>
                  const params = {
                    ...filterData,
                    spuId,
                    spuCode: detailInfo.spuCode,
                  }
                  startEdit(setiscalcEdit, () => spuEditMeasureInfo(params))
                } else {
                  FormStyleCalc.setFieldsValue({
                    ...detailInfo,
                  })
                  setiscalcEdit(true)
                }
              }}
            >
              {iscalcEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {iscalcEdit ? (
              <Button
                onClick={() => {
                  setiscalcEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline className="sep_forminline_style" editConfig={useFormCalc({ DICTDATA })} form={FormStyleCalc} />
      </Descriptions>
      <Descriptions
        title="款式图"
        extra={
          <Space>
            <PermissionButton
              permission="editSpuPicture"
              type="primary"
              loading={ispedding}
              onClick={async () => {
                if (isuploadEdit) {
                  const data = await FormStyleUpload.validateFields()
                  const entries = Object.entries(data).map(([key, value]) => {
                    return [key, value === undefined || value === null ? '' : value]
                  })
                  const filterData = Object.fromEntries(entries) as Record<string, any>
                  const params = {
                    ...filterData,
                    spuId,
                    spuCode: detailInfo.spuCode,
                  }
                  startEdit(setisuploadEdit, () => spuEditPicture(params))
                } else {
                  setisuploadEdit(true)
                }
              }}
            >
              {isuploadEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isuploadEdit ? (
              <Button
                onClick={() => {
                  setisuploadEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormVertical editConfig={useFormUpload({ isuploadEdit })} form={FormStyleUpload} />
      </Descriptions>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Modal
        title="修正吊牌价"
        open={tagPriceModal.open}
        maskClosable
        onCancel={tagPriceModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={tagPriceModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={tagPriceModal.confirmLoading}
                onClick={() => {
                  const preOriginSalePrice = detailInfo.originSalePrice
                  const originSalePrice = tagPriceModal.form?.getFieldValue('originSalePrice')
                  if (preOriginSalePrice == originSalePrice) {
                    message.warning('您输入的吊牌价与原始吊牌价相同！')
                    return
                  }
                  tagPriceModal.handleSubmit(editTagPriceReq)
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'originSalePrice',
              label: '修正后的吊牌价',
              type: 'InputNumber',
              placeholder: '请输入修正后的吊牌价',
              rules: [
                {
                  required: true,
                  message: '请输入修正后的吊牌价',
                },
              ],
              config: {
                precision: 2,
                min: 0,
              },
            },
            {
              name: 'fixReason',
              label: '修正原因',
              type: 'Input',
              placeholder: '请输入修正原因',
              rules: [
                {
                  required: true,
                  message: '请输入修正原因',
                },
              ],
              config: {
                showCount: true,
                maxLength: 50,
              },
            },
          ]}
          form={tagPriceModal.form}
        />
      </Modal>
    </DetailContainer>
  )
}
export default Index
